# -*- coding: utf-8 -*-
import asyncio
import datetime
import os
from PyQt5.QtCore import pyqtSignal, QObject

import blivedm
import blivedm.models.open_live as open_models
import blivedm.models.web as web_models
import blivedm.live_data as live_data
import blivedm.monitors
import blivedm.monitors.open_live_monitor
import blivedm.utils as utils
import blivedm.date_recorder.date_recorder as DailyRecorder 


ACCESS_KEY_ID = 'LPzjZVlGCRmbSzRbuL3okaaH'
ACCESS_KEY_SECRET = 'FrPaCQr4wTSvyma3LgEt5wsf2ug2YI'
APP_ID = 1746295470759

blind_gift_id_to_name = {32251:'心动盲盒'}
blind_gift_id_to_price = {32251:15000}

class open_live_monitor(QObject):

    message_signal = pyqtSignal(str)

    def __init__(
        self,
        room_owner_auth_code: str
    ):
        super().__init__()
        self.access_key_id = ACCESS_KEY_ID
        self.access_key_secret = ACCESS_KEY_SECRET
        self.app_id = APP_ID
        self.room_owner_auth_code = room_owner_auth_code
        self.client = None
        self.live_data = live_data.live_data()
        self.recorder = DailyRecorder.DailyRecorder(4,0,0)

    def send_message_to_window(self, message:str):
        self.message_signal.emit(message)

    async def start_monitoring(self):
        self.client = blivedm.OpenLiveClient(
            access_key_id=self.access_key_id,
            access_key_secret=self.access_key_secret,
            app_id=self.app_id,
            room_owner_auth_code=self.room_owner_auth_code,
        )
        handler = self.MyHandler(self)
        self.client.set_handler(handler)
        
        self.client.start()
        try:
            print("join")
            await self.client.join()
        finally:
            print("stop")
            await self.stop_monitoring()

    async def stop_monitoring(self):
        if hasattr(self, 'client') and self.client:
            try:
                if self.client.is_running:
                    await self.sample_callback()
                    await self.client.stop_and_close()
                else:
                    print("client has cancled!")
            except Exception as e:
                print(f"Error while stopping client: {e}")
            finally:
                self.client = None

    class MyHandler(blivedm.BaseHandler):
        def __init__(self, monitor : 'open_live_monitor'):
            super().__init__()
            self.monitor = monitor

        def _on_heartbeat(self, client: blivedm.OpenLiveClient, message: web_models.HeartbeatMessage):
            print(f'[{client.room_id}] 心跳')

        def _on_open_live_danmaku(self, client: blivedm.OpenLiveClient, message: open_models.DanmakuMessage):
            print(f'[{message.room_id}] {message.uname}：{message.msg}')
            self.monitor.send_message_to_window(f'[{message.room_id}] {message.uname}：{message.msg}')

        def _on_open_live_gift(self, client: blivedm.OpenLiveClient, message: open_models.GiftMessage):
            coin_type = '金瓜子' if message.paid else '银瓜子'
            total_coin = message.price * message.gift_num
            print(f'[{message.room_id}] {message.uname} 赠送{message.gift_name}x{message.gift_num}'
                  f' （{coin_type}x{total_coin}）')
            is_blind_gift = message.blind_gift_info.status
            if is_blind_gift and coin_type == '金瓜子':
                self.monitor.live_data.recieve_manghe(
                    message.uname, message.gift_num, blind_gift_id_to_name.get(message.blind_gift_info.blind_gift_id, "未知盲盒"), 
                    blind_gift_id_to_price.get(message.blind_gift_info.blind_gift_id, 0) / 1000, message.gift_name, message.price / 1000, message.timestamp)
            elif coin_type == "金瓜子":
                self.monitor.live_data.recieve_gift(message.uname, message.gift_num, message.gift_name, message.price / 1000, message.timestamp)
            

        def _on_open_live_buy_guard(self, client: blivedm.OpenLiveClient, message: open_models.GuardBuyMessage):
            print(f'[{message.room_id}] {message.user_info.uname} 购买 大航海等级={message.guard_level}')
            guard_type = ''
            if message.guard_level == 3:
                guard_type = '舰长'
            elif message.guard_level == 2:
                guard_type = '提督'
            elif message.guard_level == 1:
                guard_type = '总督'
            guard_num = ''
            if message.guard_unit != '月':
                guard_num = message.guard_unit
            else:
                guard_num = str(message.guard_num) + message.guard_unit
            self.monitor.live_data.recieve_guard(message.user_info.uname, guard_type, guard_num, message.price / 1000, 
                                                                        "", message.timestamp)
            

        def _on_open_live_super_chat(
            self, client: blivedm.OpenLiveClient, message: open_models.SuperChatMessage
        ):
            print(f'[{message.room_id}] 醒目留言 ¥{message.rmb} {message.uname}：{message.message}')
            self.monitor.live_data.recieve_superchat(message.uname, message.rmb, message.message, message.start_time)

        # def _on_open_live_super_chat_delete(
        #     self, client: blivedm.OpenLiveClient, message: open_models.SuperChatDeleteMessage
        # ):
        #     print(f'[{message.room_id}] 删除醒目留言 message_ids={message.message_ids}')

        # def _on_open_live_like(self, client: blivedm.OpenLiveClient, message: open_models.LikeMessage):
        #     print(f'[{message.room_id}] {message.uname} 点赞')

        # def _on_open_live_enter_room(self, client: blivedm.OpenLiveClient, message: open_models.RoomEnterMessage):
        #     print(f'[{message.room_id}] {message.uname} 进入房间')

        # def _on_open_live_start_live(self, client: blivedm.OpenLiveClient, message: open_models.LiveStartMessage):
        #     print(f'[{message.room_id}] 开始直播')

        def _on_open_live_end_live(self, client: blivedm.OpenLiveClient, message: open_models.LiveEndMessage):
            print(f'[{message.room_id}] 结束直播')
            asyncio.create_task(self.monitor.sample_callback())

    async def sample_callback(self):
        date = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M")
        year, month, day, hour, minute = date.split('-')
        print(f"开始处理日期: {year}-{month}-{day}-{hour}-{minute}")

        client_name = str(self.client.room_id)
        if utils.which_system() == 'linux':
            file_path = f"/home/data/{client_name}/{year}年{month}月/"
            await utils.async_ensure_path_exists(file_path)
            print("当前是Linux系统")
        elif utils.which_system() == 'windows':
            file_path = ""
            print("当前是Windows系统")
        else:
            print("其他操作系统")
        
        # 每日礼物处理(顺序执行)
        gift_path = file_path + f"[{client_name}]{year}年{month}月{day}日礼物列表.xlsx"
        
        # 1. 处理SC消息
        sc_df = await self.live_data.transfer_superchat()
        await utils.async_write_df_to_excel(sc_df, gift_path, "superchat")
        
        # 2. 处理普通礼物
        gift_df = await self.live_data.transfer_gift()
        await utils.async_write_df_to_excel(gift_df, gift_path, "礼物")
        
        # 3. 处理盲盒礼物
        manghe_df = await self.live_data.transfer_manghe()
        await utils.async_write_df_to_excel(manghe_df, gift_path, "盲盒礼物")
        
        # 4. 处理舰长数据
        guard_df = await self.live_data.transfer_guard()
        await utils.async_write_df_to_excel(guard_df, gift_path, "大航海")


# 使用示例
if __name__ == '__main__':
    room_owner_auth_code = 'EN2I51220AO07'

    monitor = open_live_monitor(room_owner_auth_code)
    try:
        if os.path.exists('app.log'):
            os.remove('app.log')
            print("app.log文件已成功删除")
    except:
        print("applog删除失败，但继续")
    try:
        asyncio.run(monitor.start_monitoring())
    finally:
        print("here")
        asyncio.run(monitor.stop_monitoring())
        pass